package com.vnt.lucene;

import com.vnt.domain.Book;
import org.apache.lucene.document.*;
import org.apache.lucene.index.IndexWriter;

import java.util.ArrayList;
import java.util.List;

public class MyWriterManager {
    LuceneUtil luceneUtil = null;
    String indexDir = null;
    public MyWriterManager(String indexDir){
        this.indexDir = indexDir;
        this.luceneUtil = new LuceneUtil(indexDir);
    }
    public static void testIndex(){
        MyWriterManager myWriterManager = new MyWriterManager("D:/VNThanh/Dev/SpringFramework/Source/workspaceJeeKepler/SpringMVC/mydemoindex");
        try {
            myWriterManager.luceneUtil.createIndexWriter();
            List<Book> bookList = getBookList();
            for (Book Book : bookList) {
              myWriterManager.addBookToIndex(Book);
            }
            myWriterManager.luceneUtil.closeWriter();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private static List<Book> getBookList() {
        List<Book> bookList = new ArrayList<Book>();
        Book book;

        for (int i = 0; i < 20; i++) {
        	book = new Book();
            book.setBook_name("Book_name " + i);
            book.setBook_author("Book_author " + i);
            book.setCategory("Category 1" + i);
            book.setNumpages(300);
            book.setPrice(200);
            bookList.add(book);
        }

        return bookList;
    }

    public void addBookToIndex(Book book) throws Exception {
        Document document = new Document();
        document.add(new StringField("name", book.getBook_name(), Field.Store.YES));
        document.add(new StringField("author", book.getBook_author(), Field.Store.YES));
        document.add(new StringField("category", book.getCategory(), Field.Store.YES));
        document.add(new IntField("numpage", book.getNumpages(), Field.Store.YES));
        document.add(new FloatField("price", book.getPrice(), Field.Store.YES));
        IndexWriter writer =  this.luceneUtil.getIndexWriter();
        writer.addDocument(document);
        writer.commit();
    }
}
